package com.powervision.sharesdkdemo.utils

import android.app.Application
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.os.Build
import android.util.Log
import android.widget.Toast
import cn.sharesdk.alipay.friends.Alipay
import cn.sharesdk.alipay.moments.AlipayMoments
import cn.sharesdk.dingding.friends.Dingding
import cn.sharesdk.douban.Douban
import cn.sharesdk.douyin.Douyin
import cn.sharesdk.dropbox.Dropbox
import cn.sharesdk.evernote.Evernote
import cn.sharesdk.facebook.Facebook
import cn.sharesdk.facebookmessenger.FacebookMessenger
import cn.sharesdk.flickr.Flickr
import cn.sharesdk.foursquare.FourSquare
import cn.sharesdk.framework.Platform
import cn.sharesdk.framework.PlatformActionListener
import cn.sharesdk.google.GooglePlus
import cn.sharesdk.hwaccount.HWAccount
import cn.sharesdk.instagram.Instagram
import cn.sharesdk.instapaper.Instapaper
import cn.sharesdk.kaixin.KaiXin
import cn.sharesdk.kakao.story.KakaoStory
import cn.sharesdk.kakao.talk.KakaoTalk
import cn.sharesdk.kuaishou.Kuaishou
import cn.sharesdk.line.Line
import cn.sharesdk.linkedin.LinkedIn
import cn.sharesdk.meipai.Meipai
import cn.sharesdk.mingdao.Mingdao
import cn.sharesdk.oasis.Oasis
import cn.sharesdk.onekeyshare.OnekeyShare
import cn.sharesdk.pinterest.Pinterest
import cn.sharesdk.pocket.Pocket
import cn.sharesdk.reddit.Reddit
import cn.sharesdk.renren.Renren
import cn.sharesdk.sina.weibo.SinaWeibo
import cn.sharesdk.snapchat.Snapchat
import cn.sharesdk.system.email.Email
import cn.sharesdk.system.text.ShortMessage
import cn.sharesdk.telecom.Telecom
import cn.sharesdk.telegram.Telegram
import cn.sharesdk.tencent.qq.QQ
import cn.sharesdk.tencent.qzone.QZone
import cn.sharesdk.tencent.weibo.TencentWeibo
import cn.sharesdk.tiktok.Tiktok
import cn.sharesdk.tumblr.Tumblr
import cn.sharesdk.twitter.Twitter
import cn.sharesdk.vkontakte.VKontakte
import cn.sharesdk.wechat.favorite.WechatFavorite
import cn.sharesdk.wechat.friends.Wechat
import cn.sharesdk.wechat.moments.WechatMoments
import cn.sharesdk.wework.Wework
import cn.sharesdk.whatsapp.WhatsApp
import cn.sharesdk.xmaccount.XMAccount
import cn.sharesdk.yixin.friends.Yixin
import cn.sharesdk.yixin.moments.YixinMoments
import cn.sharesdk.youdao.YouDao
import cn.sharesdk.youtube.Youtube
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.huawei.hms.framework.common.Logger
import com.mob.MobSDK
import com.powervision.sharesdkdemo.R
import com.powervision.sharesdkdemo.app.MyApp
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.util.*

/**
 * @auth: njb
 * @date: 2021/10/18 15:59
 * @desc: 描述
 */
class ShareUtils private constructor() {
    fun initMobSDK(app: Application?) {
        MobSDK.init(app, MobSDK.getAppkey(), MobSDK.getAppSecret())
    }

    /**
     * 系统分享
     *
     * @param context
     * @param mVideoFilePath
     */
    private fun shareVideoBySystem(context: Context, mVideoFilePath: String) {
        val videoIntent = Intent(Intent.ACTION_SEND)
        videoIntent.type = "video/*"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            videoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        val uri = FileUtils.getVideoUri(mVideoFilePath)
        Logger.w("uri", uri)
        videoIntent.putExtra(Intent.EXTRA_STREAM, uri)
        context.startActivity(Intent.createChooser(videoIntent,
                context.resources.getString(R.string.share_string)))
    }

    companion object {
        private const val Tag = "share_util"

        @Volatile
        private var instance: ShareUtils? = null

        /**
         * 获取api
         *
         * @return
         */
        var api: IWXAPI? = null
        @JvmStatic
        fun get(): ShareUtils? {
            if (instance == null) {
                synchronized(ShareUtils::class.java) {
                    if (instance == null) {
                        instance = ShareUtils()
                    }
                }
            }
            return instance
        }

        /**
         * 注册到微信
         *
         * @param context
         */
        @JvmStatic
        fun regToWx(context: Context?) {
            // 通过WXAPIFactory工厂，获取IWXAPI的实例
            api = WXAPIFactory.createWXAPI(context, null)
            // 将应用的appId注册到微信
            api?.registerApp(AppConstant.WX_APP_ID)
        }

        /**
         * 分享到微信或者朋友圈
         *
         * @param platformName
         * @param title
         * @param url
         * @param content
         * @param imgUrl
         */
        @JvmStatic
        fun shareToWeChat(platformName: String, title: String?, url: String?, content: String?, imgUrl: String?) {
            val oks = OnekeyShare()
            //指定分享的平台，如果为空，还是会调用九宫格的平台列表界面
            setPlatForm(oks, platformName)
            // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
            oks.setTitle(title)
            // titleUrl是标题的网络链接，仅在Linked-in,QQ和QQ空间使用
            oks.setTitleUrl(url)
            // text是分享文本，所有平台都需要这个字段
            oks.text = content
            //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
            oks.setImageUrl(imgUrl)
            // url仅在微信（包括好友和朋友圈）中使用
            oks.setUrl(url)
            //分享回调
            oks.callback = object : PlatformActionListener {
                override fun onComplete(platform: Platform, successCode: Int, hashMap: HashMap<String, Any>) {
                    // 分享成功回调
                    Log.d("--shareSuccess--", "$successCode 分享成功 ")
                    Toast.makeText(MyApp.getInstance(), "分享成功", Toast.LENGTH_SHORT).show()
                }

                override fun onError(platform: Platform, errorCode: Int, throwable: Throwable) {
                    // 分享失败回调
                    // 失败的回调，arg:平台对象，arg1:表示当前的动作(9表示分享)，arg2:异常信息
                    Log.d("--shareError--", errorCode.toString() + " 分享失败 " + throwable.message)
                    Toast.makeText(MyApp.getInstance(), "分享失败", Toast.LENGTH_SHORT).show()
                }

                override fun onCancel(platform: Platform, cancelCode: Int) {
                    // 分享取消回调
                    Log.d("--shareError--", "$cancelCode 取消分享 ")
                    Toast.makeText(MyApp.getInstance(), "取消分享", Toast.LENGTH_SHORT).show()
                }
            }
            //去除分享正在后台的提示
            oks.setDisappearShareToast(false)
            //关闭一键分享默认ui
            // oks.setSilent(false);
            //oks.addHiddenPlatform(Wechat.NAME);
            // oks.addHiddenPlatform(WechatMoments.NAME);
            /*oks.addHiddenPlatform(WechatFavorite.NAME);
        oks.addHiddenPlatform(QQ.NAME);
        oks.addHiddenPlatform(QZone.NAME);
        oks.addHiddenPlatform(SinaWeibo.NAME);
        oks.addHiddenPlatform(Douyin.NAME);
        oks.addHiddenPlatform(Facebook.NAME);
        oks.addHiddenPlatform(Twitter.NAME);
        oks.addHiddenPlatform(ShortMessage.NAME);
        oks.addHiddenPlatform(FacebookMessenger.NAME);
        oks.addHiddenPlatform(WhatsApp.NAME);
        oks.addHiddenPlatform(LinkedIn.NAME);
        oks.addHiddenPlatform(TencentWeibo.NAME);
        oks.addHiddenPlatform(Renren.NAME);
        oks.addHiddenPlatform(KaiXin.NAME);
        oks.addHiddenPlatform(Email.NAME);
        oks.addHiddenPlatform(YouDao.NAME);
        oks.addHiddenPlatform(Evernote.NAME);
        oks.addHiddenPlatform(GooglePlus.NAME);
        oks.addHiddenPlatform(Pinterest.NAME);
        oks.addHiddenPlatform(Flickr.NAME);
        oks.addHiddenPlatform(Dropbox.NAME);
        oks.addHiddenPlatform(VKontakte.NAME);
        oks.addHiddenPlatform(Instagram.NAME);
        oks.addHiddenPlatform(Yixin.NAME);
        oks.addHiddenPlatform(YixinMoments.NAME);
        oks.addHiddenPlatform(Mingdao.NAME);
        oks.addHiddenPlatform(Line.NAME);
        oks.addHiddenPlatform(KakaoTalk.NAME);
        oks.addHiddenPlatform(KakaoStory.NAME);
        oks.addHiddenPlatform(Pocket.NAME);
        oks.addHiddenPlatform(Instapaper.NAME);
        oks.addHiddenPlatform(Alipay.NAME);
        oks.addHiddenPlatform(AlipayMoments.NAME);
        oks.addHiddenPlatform(Dingding.NAME);
        oks.addHiddenPlatform(Youtube.NAME);
        oks.addHiddenPlatform(Telegram.NAME);
        oks.addHiddenPlatform(Yixin.NAME);
        oks.addHiddenPlatform(Douban.NAME);
        oks.addHiddenPlatform(Tumblr.NAME);
        oks.addHiddenPlatform(HWAccount.NAME);
        oks.addHiddenPlatform(XMAccount.NAME);
        oks.addHiddenPlatform(Oasis.NAME);
        oks.addHiddenPlatform(Snapchat.NAME);
        oks.addHiddenPlatform(FourSquare.NAME);
        oks.addHiddenPlatform(Wework.NAME);
        oks.addHiddenPlatform(Kuaishou.NAME);
        oks.addHiddenPlatform(Tiktok.NAME);
        oks.addHiddenPlatform(Reddit.NAME);
        oks.addHiddenPlatform(Meipai.NAME);*/
            // 启动分享
            oks.show(MobSDK.getContext())
        }

        /**
         * 分享图片
         *
         * @param context
         * @param mImageFilePath
         */
        fun shareImageBySystem(context: Context, mImageFilePath: String?) {
            val imageIntent = Intent(Intent.ACTION_SEND)
            imageIntent.type = "image/*"
            imageIntent.putExtra(Intent.EXTRA_STREAM, FileUtils.getUriFromPath(mImageFilePath))
            context.startActivity(Intent.createChooser(imageIntent, context.resources.getString(R.string.share_string)))
        }

        /**
         * 分享文本
         *
         * @param context
         * @param title
         * @param content
         */
        fun shareTextBySystem(context: Context, title: String?, content: String?) {
            var share_intent = Intent()
            share_intent.action = Intent.ACTION_SEND //设置分享行为
            share_intent.type = "text/plain" //设置分享内容的类型
            share_intent.putExtra(Intent.EXTRA_SUBJECT, title) //添加分享内容标题
            share_intent.putExtra(Intent.EXTRA_TEXT, content) //添加分享内容
            //创建分享的Dialog
            share_intent = Intent.createChooser(share_intent, context.resources.getString(R.string.share_string))
            context.startActivity(share_intent)
        }

        /**
         * 设置指定的分享平台
         *
         * @param oks
         * @param platformName
         */
        private fun setPlatForm(oks: OnekeyShare, platformName: String) {
            when (platformName) {
                "1" -> oks.setPlatform(Wechat.NAME)
                "2" -> oks.setPlatform(WechatMoments.NAME)
                "3" -> oks.setPlatform(WechatFavorite.NAME)
                "4" -> oks.setPlatform(QQ.NAME)
                "5" -> oks.setPlatform(QZone.NAME)
                "6" -> oks.setPlatform(SinaWeibo.NAME)
                "7" -> oks.setPlatform(Douyin.NAME)
                "8" -> oks.setPlatform(Facebook.NAME)
                "9" -> oks.setPlatform(Twitter.NAME)
                "10" -> oks.setPlatform(ShortMessage.NAME)
                "11" -> oks.setPlatform(FacebookMessenger.NAME)
                "12" -> oks.setPlatform(WhatsApp.NAME)
                "13" -> oks.setPlatform(LinkedIn.NAME)
                "14" -> oks.setPlatform(TencentWeibo.NAME)
                "15" -> oks.setPlatform(Renren.NAME)
                "16" -> {
                    oks.setPlatform(KaiXin.NAME)
                    oks.setPlatform(Email.NAME)
                }
                "17" -> oks.setPlatform(Email.NAME)
                "18" -> oks.setPlatform(YouDao.NAME)
                "19" -> oks.setPlatform(Evernote.NAME)
                "20" -> oks.setPlatform(GooglePlus.NAME)
                "21" -> oks.setPlatform(Pinterest.NAME)
                "22" -> oks.setPlatform(Flickr.NAME)
                "23" -> oks.setPlatform(Dropbox.NAME)
                "24" -> oks.setPlatform(VKontakte.NAME)
                "25" -> oks.setPlatform(Instagram.NAME)
                "26" -> oks.setPlatform(Yixin.NAME)
                "27" -> oks.setPlatform(YixinMoments.NAME)
                "28" -> oks.setPlatform(YixinMoments.NAME)
                "29" -> oks.setPlatform(Mingdao.NAME)
                "30" -> oks.setPlatform(Line.NAME)
                "31" -> oks.setPlatform(KakaoTalk.NAME)
                "32" -> oks.setPlatform(KakaoStory.NAME)
                "33" -> oks.setPlatform(Pocket.NAME)
                "34" -> oks.setPlatform(Instapaper.NAME)
                "35" -> oks.setPlatform(Alipay.NAME)
                "36" -> oks.setPlatform(AlipayMoments.NAME)
                "37" -> oks.setPlatform(Dingding.NAME)
                "38" -> oks.setPlatform(Youtube.NAME)
                "39" -> oks.setPlatform(Meipai.NAME)
                "40" -> oks.setPlatform(Telegram.NAME)
                "41" -> oks.setPlatform(Reddit.NAME)
                "42" -> oks.setPlatform(Telecom.NAME)
                "43" -> oks.setPlatform("")
                "44" -> oks.setPlatform(Mingdao.NAME)
                "45" -> oks.setPlatform(Douban.NAME)
                "46" -> oks.setPlatform("")
                "47" -> oks.setPlatform("")
                "48" -> oks.setPlatform(Tumblr.NAME)
                "49" -> oks.setPlatform(HWAccount.NAME)
                "50" -> oks.setPlatform(XMAccount.NAME)
                "51" -> oks.setPlatform(Oasis.NAME)
                "52" -> oks.setPlatform(Snapchat.NAME)
                "53" -> oks.setPlatform(FourSquare.NAME)
                "54" -> oks.setPlatform(Wework.NAME)
                "55" -> oks.setPlatform(Kuaishou.NAME)
                "56" -> oks.setPlatform(Tiktok.NAME)
                else -> {
                }
            }
        }

        /**
         * 跳转到小程序
         *
         * @param path 商品详情
         * 订单详情
         */
        fun launchMiniProgram(path: String?) {
            val req = WXLaunchMiniProgram.Req()
            req.userName = AppConstant.SHOP_WX_MINI_PROGRAM_ID // 填小程序原始id
            req.path = path // 拉起小程序页面的可带参路径，不填默认拉起小程序首页
            req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
            api!!.sendReq(req)
        }

        /**
         * 分享到微信小程序
         *
         * @param imgUrl 封面
         * @param title  标题
         * @param desc   描述
         * @param path   小程序页面路径 例如 AppConstant.WX_MINI_ACCOUNT_SHARE_PATH + 需要的参数
         */
        fun shareToWxMiniProgram(imgUrl: String?, title: String?, desc: String?, path: String?) {
            val miniProgramObj = WXMiniProgramObject()
            miniProgramObj.webpageUrl = "https://mmbizurl.cn/s/EweoV15JB" // 兼容低版本的网页链接
            miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE // 正式版:0，测试版:1，体验版:2
            miniProgramObj.userName = AppConstant.WX_MINI_PROGRAM_ID // 小程序原始id
            miniProgramObj.path = path //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
            val msg = WXMediaMessage(miniProgramObj)
            msg.title = title // 小程序消息title
            msg.description = desc // 小程序消息desc
            Thread(Runnable {
                val bmp: Bitmap?
                try {
                    bmp = Glide.with(MyApp.getInstance())
                            .asBitmap()
                            .load(imgUrl)
                            .centerCrop()
                            .into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                            .get()
                    if (bmp == null) {
                        return@Runnable
                    }
                    var bitmap = BitMapUtils.drawWXMiniBitmap(bmp, bmp.height * 5 / 4, bmp.height)
                    if (BitMapUtils.isOverSize(bitmap, 128)) { //是否需要压缩，不需要的话设置bitmap宽高
                        bitmap = BitMapUtils.setBitmapSize(bitmap, 300, 260)
                    }
                    //bitmap转成字节流
                    msg.thumbData = BitMapUtils.bmpToByteArray(bitmap, true)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                val req = SendMessageToWX.Req()
                req.transaction = buildTransaction("miniProgram")
                req.message = msg
                req.scene = SendMessageToWX.Req.WXSceneSession // 目前只支持会话
                api!!.sendReq(req)
            }).start()
        }

        private fun buildTransaction(type: String?): String {
            return if (type == null) System.currentTimeMillis().toString() else type + System.currentTimeMillis()
        }
    }
}